package cn.app.edu.projectpracticeofpracticaltraining.util;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtil {

    public static void enqueue(String url, String cookie, FormBody formBody, Callback callback) {

        Request.Builder builder = new Request.Builder().url(url);
        if (formBody != null) {
            builder.post(formBody);
        }
        if (cookie != null) {
            builder.header("cookie", cookie);
        }
        Request build = builder.build();
        new OkHttpClient()
                .newCall(build)
                .enqueue(callback);
    }

    public static void execute(String url, String cookie, FormBody formBody, final MyCallback myCallback) {

        Request.Builder builder = new Request.Builder().url(url);
        if (formBody != null) {
            builder.post(formBody);
        }
        if (cookie != null) {
            builder.header("cookie", cookie);
        }
        final Request build = builder.build();
        final Call call = new OkHttpClient().newCall(build);

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Response execute = call
                                    .execute();
                            String body = execute.body().string();
                            myCallback.runCallback(body);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

        ).start();

    }

    public interface MyCallback {
        void runCallback(String body);
    }

}
